const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const merge = require('webpack-merge');
const webpackBaseConfig = require('./webpack.base.config.js');
const fs = require('fs');
const axios = require('axios');
const bodyParser = require('body-parser');
const queryString = require('querystring');
const URL = 'http://59.110.243.101';

fs.open('./src/config/env.js', 'w', function(err, fd) {
    const buf = 'export default "development";';
    fs.write(fd, buf, 0, buf.length, 0, function(err, written, buffer) {});
});

module.exports = merge(webpackBaseConfig, {
    devtool: '#source-map',
    devServer: {
        before(app) {
            app.use(bodyParser.json());
            app.use(bodyParser.urlencoded({ extended: false }));

            // login
            app.post('/face/api/face/equaker/login', (req, res) => {
                post(URL + '/face/api/face/equaker/login', req.body)
                    .then(response => {
                        res.json(response.data)
                    }).catch(e => {
                    console.log(e)
                })
            });
        }
    },
    output: {
        publicPath: '/dist/',
        filename: '[name].js',
        chunkFilename: '[name].chunk.js'
    },
    plugins: [
        new ExtractTextPlugin({
            filename: '[name].css',
            allChunks: true
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendors',
            filename: 'vendors.js'
        }),
        new HtmlWebpackPlugin({
            filename: '../index.html',
            template: './src/template/index.ejs',
            inject: false
        })
    ]
});

// 封装post转发机制，用于解决node下axios post方法失效问题
function post(url, params) {
    return axios.post(url, params?queryString.stringify(params):'')
}